package it.appcatalogobase;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.text.Html;
import android.util.Log;
import android.widget.Toast;

public class MyAsyncTask extends AsyncTask<Void, Void, Void> {
	
	private ProgressDialog progressDialog;
	private InputStream inputStream = null;
	private InputStream inputStream2 = null;
	private InputStream inputStreamDS = null;
	public InputStream getInputStreamDS() {
		return inputStreamDS;
	}


	public void setInputStreamDS(InputStream inputStreamDS) {
		this.inputStreamDS = inputStreamDS;
	}


	public InputStream getInputStreamCS() {
		return inputStreamCS;
	}


	public void setInputStreamCS(InputStream inputStreamCS) {
		this.inputStreamCS = inputStreamCS;
	}


	private InputStream inputStreamCS = null;
	private String result = ""; 
	private String result2 = ""; 
	private String resultDS = ""; 
	private String resultCS = ""; 
	private Activity a;
	private String url;
	private NetworkInfo intC;
	private Properties properties;
	
    public InputStream getInputStream2() {
		return inputStream2;
	}


	public void setInputStream2(InputStream inputStream2) {
		this.inputStream2 = inputStream2;
	}


	public String getResult2() {
		return result2;
	}


	public void setResult2(String result2) {
		this.result2 = result2;
	}


	public String getUrl() {
		return url;
	}


	public void setUrl(String url) {
		this.url = url;
	}


	public NetworkInfo getIntC() {
		return intC;
	}


	public void setIntC(NetworkInfo intC) {
		this.intC = intC;
	}


	public ProgressDialog getProgressDialog() {
		return progressDialog;
	}


	public void setProgressDialog(ProgressDialog progressDialog) {
		this.progressDialog = progressDialog;
	}


	public InputStream getInputStream() {
		return inputStream;
	}


	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}


	public String getResult() {
		return result;
	}


	public void setResult(String result) {
		this.result = result;
	}


	public Activity getA() {
		return a;
	}


	public void setA(Activity a) {
		this.a = a;
	}


	public MyAsyncTask(){
    	
    }
	
	public MyAsyncTask(String url, Activity a){
		this.a=a;
		this.url=url;
		this.progressDialog= new ProgressDialog(a);
		this.properties = new Properties();
		
	}
    
    
    protected void onPreExecute() {
        progressDialog.setMessage("...Sincronizzo i dati...");
        progressDialog.show();
        progressDialog.setOnCancelListener(new OnCancelListener() {
            public void onCancel(DialogInterface arg0) {
                MyAsyncTask.this.cancel(true);
            }
        });
    }  
        @Override
        protected Void doInBackground(Void... params) {
        AssetManager assetManager = a.getAssets();
        InputStream inputStream=null;
		try {
			inputStream = assetManager.open("config.properties");
			properties.load(inputStream);
		} catch (IOException e5) {
			// TODO Auto-generated catch block
			e5.printStackTrace();
		}
		
        ConnectivityManager conMgr = (ConnectivityManager) a.getSystemService(a.CONNECTIVITY_SERVICE);
        intC = conMgr.getActiveNetworkInfo();

//            String url_select = "http://yoururlhere.com";

//            ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
       if(intC!=null && intC.isConnected() && intC.isAvailable()){
            try {
                // Set up HTTP post

                // HttpClient is more then less deprecated. Need to change to URLConnection
                HttpClient httpClient = new DefaultHttpClient();
                HttpClient httpClient2 = new DefaultHttpClient();
                HttpClient httpClientDS = new DefaultHttpClient();
                HttpClient httpClientCS = new DefaultHttpClient();
//                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//                nameValuePairs.add(new BasicNameValuePair("year","1980"));
                HttpGet httpGet = new HttpGet(properties.getProperty("indirizzoCat"));
//                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpGet httpGet2 = new HttpGet(properties.getProperty("indirizzoPro"));
                HttpGet httpGetDS = new HttpGet(properties.getProperty("indirizzoDoveSiamo"));
                HttpGet httpGetCS = new HttpGet(properties.getProperty("indirizzoChiSiamo"));
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpResponse httpResponse2 = httpClient2.execute(httpGet2);
                HttpResponse httpResponseDS = httpClientDS.execute(httpGetDS);
                HttpResponse httpResponseCS = httpClientCS.execute(httpGetCS);
                Log.i("JSON",httpResponse.getStatusLine().toString());
                Log.i("JSON",httpResponse2.getStatusLine().toString());
                Log.i("JSON",httpResponseDS.getStatusLine().toString());
                Log.i("JSON",httpResponseCS.getStatusLine().toString());
                HttpEntity httpEntity = httpResponse.getEntity();
                HttpEntity httpEntity2 = httpResponse2.getEntity();
                HttpEntity httpEntityDS = httpResponseDS.getEntity();
                HttpEntity httpEntityCS = httpResponseCS.getEntity();
//                Log.v("JSON",httpEntity.getContent().toString());
                // Read content & Log
                inputStream = httpEntity.getContent();
                inputStream2 = httpEntity2.getContent();
                inputStreamDS = httpEntityDS.getContent();
                inputStreamCS = httpEntityCS.getContent();
//                Log.v("JSON",inputStream.toString());
            } catch (UnsupportedEncodingException e1) {
                Log.e("UnsupportedEncodingException", e1.toString());
                e1.printStackTrace();
            } catch (ClientProtocolException e2) {
                Log.e("ClientProtocolException", e2.toString());
                e2.printStackTrace();
            } catch (IllegalStateException e3) {
                Log.e("IllegalStateException", e3.toString());
                e3.printStackTrace();
            } catch (IOException e4) {
                Log.e("IOException", e4.toString());
                e4.printStackTrace();
            }
            // Convert response to string using String Builder
            try {
                BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
                StringBuilder sBuilder = new StringBuilder();

                String line = null;
                while ((line = bReader.readLine()) != null) {
                    sBuilder.append(line + "\n");
                }

                inputStream.close();
                result = sBuilder.toString();
                
                BufferedReader bReader2 = new BufferedReader(new InputStreamReader(inputStream2, "iso-8859-1"), 8);
                StringBuilder sBuilder2 = new StringBuilder();

                String line2 = null;
                while ((line2 = bReader2.readLine()) != null) {
                    sBuilder2.append(line2 + "\n");
                }

                inputStream2.close();
                result2 = sBuilder2.toString();
                
                BufferedReader bReaderDS = new BufferedReader(new InputStreamReader(inputStreamDS, "iso-8859-1"), 8);
                StringBuilder sBuilderDS = new StringBuilder();

                String lineDS = null;
                while ((lineDS = bReaderDS.readLine()) != null) {
                    sBuilderDS.append(lineDS + "\n");
                }

                inputStreamDS.close();
                resultDS = sBuilderDS.toString();
                
                BufferedReader bReaderCS = new BufferedReader(new InputStreamReader(inputStreamCS, "iso-8859-1"), 8);
                StringBuilder sBuilderCS = new StringBuilder();

                String lineCS = null;
                while ((lineCS = bReaderCS.readLine()) != null) {
                    sBuilderCS.append(lineCS + "\n");
                }

                inputStreamCS.close();
                resultCS = sBuilder2.toString();
                
            }catch (Exception e) {
                Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
            }
            
            
            //parse JSON data
            try {
            	CategoriaDataSource data = new CategoriaDataSource(a);
            	data.open();
            	data.deleteCategorie();
            	ProdottoDataSource dataPr = new ProdottoDataSource(a);
            	dataPr.open();
                dataPr.deleteProdotti();
                DoveSiamoDataSource dataDS = new DoveSiamoDataSource(a);
            	dataDS.open();
                dataDS.deleteDoveSiamoAll();
                ChiSiamoDataSource dataCS = new ChiSiamoDataSource(a);
            	dataCS.open();
                dataCS.deleteChiSiamoAll();
                JSONArray jArray = new JSONArray(result);    
                HashMap<Integer,String> catTemp = new HashMap();
                for(int i=0; i < jArray.length(); i++) {

                    JSONObject jObject = jArray.getJSONObject(i);
                    Log.v("JSON", "CATEGORIA:");
                    int id = jObject.getInt("id");
                    Log.v("JSON", String.valueOf(jObject.getInt("id")));
                    String nome="";
                    String descrizione="";
					try {
						nome = URLDecoder.decode(Html.fromHtml(jObject.getString("titolo")).toString(), "ISO-8859-1");
						Log.v("JSON", nome);
	                    descrizione = URLDecoder.decode(Html.fromHtml(jObject.getString("descr")).toString(), "ISO-8859-1");
	                    Log.v("JSON", descrizione);
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                    
                    catTemp.put(id, nome);
                    data.createCategoria(nome, descrizione);
//                    String tab1_text = jObject.getString("tab1_text");
//                    int active = jObject.getInt("active");
                } // End Loop
                
                JSONArray jArray2 = new JSONArray(result2);    
                for(int i=0; i < jArray2.length(); i++) {
                	JSONObject jObject = jArray2.getJSONObject(i);
                	
                	String nome="";
                    String descrizione="";
                    String imm="";
                    int cat=0;
                    String des_short="";
					try {
						nome = URLDecoder.decode(Html.fromHtml(jObject.getString("titolo")).toString(), "ISO-8859-1");
						Log.v("JSON", nome);
	                    descrizione = URLDecoder.decode(Html.fromHtml(jObject.getString("descr")).toString(), "ISO-8859-1");
	                    Log.v("JSON", descrizione);
	                    imm = URLDecoder.decode(Html.fromHtml(jObject.getString("img")).toString(), "ISO-8859-1");
	                    Log.v("JSON", descrizione);
	                    cat = jObject.getInt("categ");
	                    Log.v("JSON", descrizione);
	                    des_short = URLDecoder.decode(Html.fromHtml(jObject.getString("descr_short")).toString(), "ISO-8859-1");
	                    Log.v("JSON", descrizione);
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                    
                    Log.v("JSON", "PRODOTTI:");
                    Log.v("JSON", String.valueOf(jObject.getInt("id")));
                    Log.v("JSON", jObject.getString("titolo"));
                    Log.v("JSON", jObject.getString("descr_short"));
                    Log.v("JSON", jObject.getString("descr"));
                    Log.v("JSON", jObject.getString("img"));
                    Log.v("JSON", jObject.getString("categ"));
                    dataPr.createProdotto(nome,descrizione,catTemp.get(cat),imm,des_short);

                    //                    dataPr.createProdotto(jObject.getString("titolo"), jObject.getString("descr"), catTemp.get(jObject.getInt("categ")), jObject.getString("img"),jObject.getString("descr_short"));
                    String[] files = a.getFilesDir().getAbsoluteFile().list();
                    boolean found = false;
                    for(String file : files){
                    	if (file.equals(jObject.getString("img")))
                    		found=true;
                    }
                    if(!found){
	                    try {
	                    	
	                    	URL url = new URL(properties.getProperty("imageDirProp")+jObject.getString("img"));
//	                        URL url = new URL("http://www.tempogara.it/arcobaleno/temp/immagini/"+jObject.getString("immagine"));
//	                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//	                        conn.setDoInput(true);
//	                        conn.connect();
	                        InputStream is = url.openStream();//conn.getInputStream();
	                        BitmapFactory.Options opt = getOptions(is, 500, 500);
	                        is.close();
	                        is = url.openStream();//conn.getInputStream();
	                        
	                        Bitmap bm = loadBitmap(is, 500, 500, opt);//decodeSampledBitmapFromStream(is, 500, 500);//BitmapFactory.decodeStream(is);
//	                        bm.recycle();
//	                        bm=null;
	                        FileOutputStream fos = a.openFileOutput(jObject.getString("img"), a.MODE_PRIVATE);
	                        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
	                        bm.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
	                        byte[] byteArray = outstream.toByteArray();
	                                 
	                        fos.write(byteArray);
	                        fos.close();
	                    } catch(Exception e) {
	                       e.printStackTrace();    
	                    }
                    }
                   
//                    String tab1_text = jObject.getString("tab1_text");
//                    int active = jObject.getInt("active");
                }
                
                JSONArray jArrayDS = new JSONArray(resultDS);
                JSONObject jObject = jArrayDS.getJSONObject(0);
                String indirizzo="";
                String mail="";
                String cell="";
                String tel="";
                String fax="";
                String lat="";
                String lon="";
				try {
					indirizzo = URLDecoder.decode(Html.fromHtml(jObject.getString("indirizzo")).toString(), "ISO-8859-1");
					Log.v("JSON", indirizzo);
                    mail = URLDecoder.decode(Html.fromHtml(jObject.getString("mail")).toString(), "ISO-8859-1");
                    Log.v("JSON", mail);
                    cell = URLDecoder.decode(Html.fromHtml(jObject.getString("cell")).toString(), "ISO-8859-1");
                    Log.v("JSON", cell);
                    tel = URLDecoder.decode(Html.fromHtml(jObject.getString("tel")).toString(), "ISO-8859-1");
                    Log.v("JSON", tel);
                    fax = URLDecoder.decode(Html.fromHtml(jObject.getString("fax")).toString(), "ISO-8859-1");
                    Log.v("JSON", fax);
                    lat = URLDecoder.decode(Html.fromHtml(jObject.getString("lat")).toString(), "ISO-8859-1");
                    Log.v("JSON", lat);
                    lon = URLDecoder.decode(Html.fromHtml(jObject.getString("long")).toString(), "ISO-8859-1");
                    Log.v("JSON", lon);
                    dataDS.createDoveSiamo(indirizzo, mail, cell, tel, fax, lat, lon);
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				JSONArray jArrayCS = new JSONArray(resultDS);
                JSONObject jObjectCS = jArrayCS.getJSONObject(0);
                String descr="";
               
				try {
					descr = URLDecoder.decode(Html.fromHtml(jObject.getString("chisiamo")).toString(), "ISO-8859-1");
					Log.v("JSON", indirizzo);
                    dataCS.createChiSiamo(descr);
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
            } catch (JSONException e) {
                Log.e("JSONException", "Error: " + e.toString());
            } // catch (JSONException e)
        	SharedPreferences prefs = a.getSharedPreferences("SyncPref", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
			editor.putBoolean("FirstSync", true);
       }
			return null;
   } // protected Void doInBackground(String... params)  

        public static int getScale(int originalWidth,int originalHeight,final int requiredWidth,final int requiredHeight){
	        	 //a scale of 1 means the original dimensions 
	        	 //of the image are maintained
	        	 int scale=1;
	        	        
	        	 //calculate scale only if the height or width of 
	        	 //the image exceeds the required value.
	        	 if((originalWidth>requiredWidth) || (originalHeight>requiredHeight)) 
	        	   {
	        	       //calculate scale with respect to
	        	    //the smaller dimension
	        	    if(originalWidth<originalHeight)
	        	   scale=Math.round((float)originalWidth/requiredWidth);
	        	    else
	        	   scale=Math.round((float)originalHeight/requiredHeight);
	        	 
	        	    }
	        	       
	        	  return scale;
        }
        
        
        public static BitmapFactory.Options getOptions(InputStream is,int requiredWidth,int requiredHeight)
     	   {
        	   
        	 BitmapFactory.Options options=new BitmapFactory.Options();
        	 //setting inJustDecodeBounds to true
        	 //ensures that we are able to measure
        	 //the dimensions of the image,without
        	 //actually allocating it memory
        	 options.inJustDecodeBounds=true;
        	   
        	 //decode the file for measurement
        	 BitmapFactory.decodeStream(is,null,options);
        	   
        	 //obtain the inSampleSize for loading a 
        	 //scaled down version of the image.
        	 //options.outWidth and options.outHeight 
        	 //are the measured dimensions of the 
        	 //original image
        	 options.inSampleSize=getScale(options.outWidth,options.outHeight, requiredWidth, requiredHeight);
        	   
        	 //set inJustDecodeBounds to false again
        	 //so that we can now actually allocate the
        	 //bitmap some memory
        	 options.inJustDecodeBounds=false;
        	 
        	 return options;
        	   
        }
        
        public Bitmap loadBitmap(InputStream is, int requiredWidth,int requiredHeight,BitmapFactory.Options options){

//         BitmapFactory.Options options= getOptions(is,requiredWidth, requiredHeight);
         return BitmapFactory.decodeStream(is, null, options);
//     	  return BitmapFactory.decodeFile(filePath,options);
      }
       
        
        protected void onPostExecute(Void v) {
                this.progressDialog.dismiss();
                if(intC!=null && intC.isConnected() && intC.isAvailable())
                	Toast.makeText(a, "Sincronizzazione effettuata", Toast.LENGTH_SHORT).show();
                else
                	Toast.makeText(a, "Sincronizzazione non effettuata, verificare la connessione", Toast.LENGTH_SHORT).show();
        } // protected void onPostExecute(Void v)
 }//class MyAsyncTask extends AsyncTask<String, String, Void>

